<template>
  <div class="wrapp">
    <div class="head">
      <div class="title">角色設置</div>
      <Button @click="back">返回上一級</Button>
    </div>
    <div class="select">
      <div class="box">
        <div class="boxHead">
          <Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="handleCheckAll">&nbsp;&nbsp;&nbsp;&nbsp;用戶</Checkbox>
          <span>{{selectData.length}}</span>
        </div>
        <div class="boxSearch">
          <Input placeholder="請輸入搜索內容" style="width:100%;" size="small" v-model="searchUserName" />
          <a class="searchIcon" @click="mao(searchUserName)">
            <Icon type="ios-search" size="20" />
          </a>
        </div>
        <div class="boxContent" id="boxContent">
          <div class="boxContentSon">
            <CheckboxGroup v-model="fruit" class="checkboxGroup" @on-change="selectFun" id="checkboxGroup">
              <div class="contentItem" v-for="(item,index) in selectData" :key="index">
                <Checkbox :label="item.userName+'/'+item.mobile+'/'+item.userId" :id="item.userName">{{item.userName}}/{{item.mobile}}</Checkbox>
              </div>
            </CheckboxGroup>
          </div>
        </div>
      </div>
      <div class="type">
        <Button type="primary" @click="addToItem('矿工')">添加至"矿工"角色</Button>
        <Button type="primary" @click="addToItem('矿场主')">添加至"矿场主"角色</Button>
        <Button type="primary" @click="addToItem('经销商')">添加至"经销商"角色</Button>
        <Button type="primary" @click="addToItem('推荐经销商')">添加至"推荐经销商"角色</Button>
        <Button type="primary" @click="addToItem('讲师')">添加至"讲师"角色</Button>
        <Button type="primary" @click="addToItem('平台')">添加至"平台"角色</Button>
        <Button type="primary" @click="addToItem('股东')">添加至"股东"角色</Button>
        <Button type="primary" @click="addToItem('员工')">添加至"员工"角色</Button>
        <Button type="primary" @click="addToItem('投资人')">添加至"投资人"角色</Button>
        <!-- <Button type="primary">添加至"矿工"角色</Button>
                <Button type="primary">添加至"矿工"角色</Button>
        <Button type="primary">添加至"矿工"角色</Button>-->
      </div>
    </div>
    <div class="banner">
      <div class="bannerItem" v-for="(wholeItem,index) in wholeArry" :key="index">
        <div class="boxHead">
          <span>{{wholeItem.name}}</span>
          <span>{{wholeItem.userAarry.length}}</span>
        </div>
        <div class="boxContent">
          <div class="boxContentSon_1">
            <div class="srcroll">
              <div class="contentItem" v-for="(userItem,ind) in wholeItem.userAarry" :key="ind">
                <span>{{userItem.userName}}</span>
                <span>{{userItem.mobile}}</span>
                <Button type="primary" size="small" style="width:55px;height:27px" @click="remove(index,ind)">移除</Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="sure">
      <Button type="primary" @click="sure">确定</Button>
    </div>

    <Modal v-model="sureCharacter" :mask-closable="false" width="1076" cancel-text @on-ok="ok">
      <div v-for="(wholeItem,index) in wholeArry" :key="index" style="margin-top:10px;">
        <h3>{{wholeItem.name}}</h3>
        <div class="sureItem" v-for="(userItem,ind) in wholeItem.userAarry" :key="ind">
          <span>{{userItem.userName}}</span>
          <span>{{userItem.mobile}}</span>
          <span style="color:red">/</span>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import apis from "../../util/apis.js";
import { equal } from 'assert';
export default {
  name: "SetCharacter",
  data() {
    return {
      searchUserName: '',
      getParams: null,
      pageTotalUser: 0,
      projectId: null,
      sureCharacter: false,
      checkAll: false,
      indeterminate: false,
      ///////装选择了数据的容器
      containerData: [],
      selectData: [],
      fruit: [],
      wholeArry: [
        {
          name: "矿工",
          userAarry: []
        },
        {
          name: "矿场主",
          userAarry: []
        },
        {
          name: "经销商",
          userAarry: []
        },
        {
          name: "推荐经销商",
          userAarry: []
        },
        {
          name: "讲师",
          userAarry: []
        },
        {
          name: "平台",
          userAarry: []
        },
        {
          name: "股东",
          userAarry: []
        },
        {
          name: "员工",
          userAarry: []
        },
        {
          name: "投资人",
          userAarry: []
        }
      ],
      userShowData: [],
      props: '',
      scroll
    };
  },
  created() {
    this.props = this.$route.query.props;
  },
  methods: {
    /////////////////////////////////获取数据源///////////////////
    getRelatedUserData() {
      let token = this.$localStorage.storageGet("TOKEN");
      if (!token) {
        this.$router.push({
          name: "Login"
        });
        return;
      }
      let url = apis.checkCharacterApi + "/" + this.projectId + "?size=" + 99999;
      this.$axios({
        method: "get",
        url: url,
        headers: {
          Authorization: "Bearer " + token
        }
      })
        .then(res => {
          if (res.status == "200") {
            let data = res.data;
            data.forEach(element => {
              let temp = {};
              temp.userName = element.userName;
              temp.mobile = element.mobile;
              temp.userId = element.userId;
              this.selectData.push(element);
            });
            let newData = [];
            data.forEach(element => {
              if (element.roles.length > 0) {
                element.roles.forEach(ele => {
                  let temp = {}
                  temp.role = ele;
                  temp.name = this.dealDataTemp(ele);
                  temp.userId = element.userId;
                  temp.userName = element.userName;
                  temp.mobile = element.mobile;
                  newData.push(temp);
                })
              }
            })

            let newData_1 = this.mapLoction(newData);
            this.wholeArry.forEach(element => {
              newData_1.forEach(ele => {
                if (element.name === ele.name) {
                  element.userAarry = ele.userAarry
                }
              })
            })
            this.pageTotalUser = parseInt(res.headers["x-total-count"]);
          } else {
            this.$Message.error(res.data.detail);
          }
        })
        .catch(err => {
          console.log(err)
          this.$Message.error(err.response.data.message);
        });
    },
    /////////根据一个相同值重组数组////////
    mapLoction(arr) {
      var map = {},
        dest = [];
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.name]) {
          dest.push({
            name: ai.name,
            userAarry: [ai]
          });
          map[ai.name] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.name == ai.name) {
              dj.userAarry.push(ai);
              break;
            }
          }
        }
      }
      return dest;
    },
    /////////////////////////角色设置///////
    setCharacterFun(param) {
      let token = this.$localStorage.storageGet("TOKEN");
      if (!token) {
        this.$router.push({
          name: "Login"
        });
        return;
      }
      let url = apis.setCharacterApi + "/" + this.projectId;
      this.$axios({
        method: "post",
        url: url,
        data: param,
        headers: {
          Authorization: "Bearer " + token
        }
      })
        .then(res => {
          if (res.status == "200") {
            this.$router.push({
              name: "ProjectDetail",
              query: {
                param: this.getParams,
                proName: "rule"
              }
            });
          } else {
            this.$Message.error(res.data.detail);
          }
        })
        .catch(err => {
          this.$Message.error(err.response.data.message);
        });
    },
    back() {
      this.$router.push({
        name: "ProjectDetail",
        query: {
          param: this.props,
          proName: "rule"
        }
      });
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;
      let arr = []
      this.selectData.forEach(element => {
        let str = '';
        str = element.userName + "/" + element.mobile + "/" + element.userId;
        arr.push(str);
      })
      if (this.checkAll) {
        this.fruit = arr;
        this.containerData = arr;
      } else {
        this.fruit = [];
        this.containerData = [];
      }


    },
    selectFun(value) {
      let len = this.selectData.length;
      if (value.length === len) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (value.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
      this.containerData = value;
      console.log(value)
    },
    addToItem(type) {
      this.wholeArry.forEach(element => {
        let temp = {};
        if (element.name === type) {
          this.containerData.forEach(ele => {
            let t = {};
            let lineIndex = ele.indexOf("/");
            let lastIndex = ele.lastIndexOf("/");
            let len = ele.length;
            t.userName = ele.slice(0, lineIndex);
            t.mobile = ele.slice(lineIndex + 1, lastIndex);
            t.userId = parseInt(ele.slice(lastIndex + 1, len));
            element.userAarry.push(t);
          });
        }
        element = this.unique(element);
      });
      this.containerData = [];
      this.fruit = [];
      this.indeterminate = false;
      this.checkAll = false;
    },
    ///////去重///////
    unique(dataAarry) {
      let result = [];
      for (let j = 0; j < dataAarry.userAarry.length; j++) {
        if (!result) {
          result.push(dataAarry.userAarry[j]);
        } else {
          let con = true;
          for (let k = 0; k < result.length; k++) {
            if (dataAarry.userAarry[j].userId === result[k].userId) {
              con = false;
              break;
            }
          }
          if (con) {
            result.push(dataAarry.userAarry[j]);
          }
        }
      }
      dataAarry.userAarry = result;
      return dataAarry;
    },
    remove(index, ind) {
      this.wholeArry[index].userAarry.splice(ind, 1);
    },
    dealDataTemp(str) {
      if (str === "01") {
        str = "矿工";
      } else if (str === "02") {
        str = "矿场主";
      } else if (str === "03") {
        str = "经销商";
      } else if (str === "04") {
        str = "推荐经销商";
      } else if (str === "05") {
        str = "讲师";
      } else if (str === "06") {
        str = "平台";
      } else if (str === "07") {
        str = "股东";
      } else if (str === "08") {
        str = "员工";
      } else if (str === "09") {
        str = "投资人";
      }
      return str;
    },
    dealData(watch, arry) {
      let newAryy = [];
      arry.forEach(element => {
        element.userAarry.forEach(ele => {
          let temp = {};
          temp.name = element.name;
          temp.userId = ele.userId;
          temp.userName = ele.userName;
          newAryy.push(temp);
        });
      });

      let map = {},
        dest = [];
      for (var i = 0; i < newAryy.length; i++) {
        var ai = newAryy[i];
        let a = "";
        if (ai.name === "矿工") {
          a = "01";
        } else if (ai.name === "矿场主") {
          a = "02";
        } else if (ai.name === "经销商") {
          a = "03";
        } else if (ai.name === "推荐经销商") {
          a = "04";
        } else if (ai.name === "讲师") {
          a = "05";
        } else if (ai.name === "平台") {
          a = "06";
        } else if (ai.name === "股东") {
          a = "07";
        } else if (ai.name === "员工") {
          a = "08";
        } else if (ai.name === "投资人") {
          a = "09";
        }
        if (!map[ai.userId]) {
          dest.push({
            userId: ai.userId,
            roles: [a]
          });
          map[ai.userId] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.userId == ai.userId) {
              dj.roles.push(a);
              break;
            }
          }
        }
      }
      let newDest = {};
      dest.forEach(element => {
        let temp = {}
        let a = element.userId;
        let b = element.roles;
        temp[a] = element.roles;
        Object.assign(newDest, temp);
      });
      if (watch === "检测") {
        return newAryy
      } else {
        return newDest;
      }

    },
    sure() {
      let a = this.dealData("检测", this.wholeArry)
      if (a.length === 0) {
        this.$Message.info({
          content: "还未配置角色",
          duration: 4
        });
        return
      }
      let newUserArry = [];
      this.selectData.forEach(element => {
        let temp = {};
        temp.userName = element.userName;
        temp.userId = element.userId;
        newUserArry.push(temp)
      });
      let userName = ''
      let control = true;
      for (let i = 0; i < newUserArry.length; i++) {
        let equal = false;
        for (let j = 0; j < a.length; j++) {
          if (newUserArry[i].userId === a[j].userId) {
            equal = true;
            break;
          }
        }
        if (!equal) {
          control = false;
          userName = newUserArry[i].userName;
          break;
        }
      }
      // newUserArry.forEach(element => {
      //   let equal = false;
      //   a.forEach(ele => {
      //     if (element.userId === ele.userId) {
      //       equal = true;
      //       return;
      //     }
      //   })
      //   if (equal) {
      //     control = true;
      //   } else {
      //     control = false;
      //     userName = element.userName;
      //     return;
      //   }
      // });
      if (!control) {
        this.$Message.info({
          content: userName + "没有选角色",
          duration: 4
        });
      } else {
        this.sureCharacter = true;
      }
    },
    ok() {
      this.setCharacterFun(this.dealData("上传", this.wholeArry));
    },

    mao(searchUserName) {
      let section = document.getElementById(searchUserName)
      if (section) {
        section.scrollIntoView()
      }
    },
  },
  mounted() {
    this.projectId = this.$route.query.param;
    this.getParams = this.$route.query.getParams;
    this.getRelatedUserData();
  }
};
</script>

<style scoped>
.banner {
  width: 1200px;
  height: auto;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
}
.bannerItem {
  height: 300px;
  width: 300px;
  border: 2px solid #dcdee2;
  border-radius: 10px;
  margin-right: 20px;
  margin-bottom: 20px;
}
.boxContentSon_1 {
  height: 250px;
  overflow: hidden;
}
.srcroll {
  height: 250px;
  overflow-y: scroll;
  overflow-x: hidden;
}
/* //////////////////////////////////////////////////// */
.wrapp {
  padding: 0 20px;
}

.head {
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  padding: 10px 5px;
  display: flex;
  justify-content: space-between;
}

.title {
  color: #666;
  font-size: 24px;
}
.select {
  margin: 50px auto;
  width: 600px;
  height: 350px;
  display: flex;
  margin-bottom: 0px;
}
.box {
  width: 280px;
  height: 300px;
  border: 2px solid #dcdee2;
  border-radius: 10px;
  margin-right: 20px;
}
.boxHead {
  padding: 0 10px;
  height: 36px;
  background: #f9fafc;
  border-bottom: 1px solid #dcdee2;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.boxSearch {
  padding: 0 5px;
  margin-top: 5px;
  position: relative;
}
.boxContent {
  margin-top: 5px;
  /* padding: 0 10px; */
}
.boxContentSon {
  height: 220px;
  overflow: hidden;
}
.checkboxGroup {
  height: 220px;
  scroll-behavior: smooth;
  overflow-y: scroll;
  overflow-x: hidden;
}
.contentItem {
  height: 44px;
  line-height: 44px;
  cursor: pointer;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.contentItem:hover {
  background: #f7f7f7;
}
.type {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 250px;
  margin-top: 30px;
}
.type button {
  width: 180px;
  height: 40px;
  margin-bottom: 10px;
  margin-right: 10px;
}
.sure {
  width: 200px;
  height: 100px;
  margin: 0 auto;
  margin-top: 30px;
}
.sureItem {
  display: inline-block;
  margin-left: 10px;
}
.searchIcon {
  position: absolute;
  right: 0;
  top: 2px;
  height: 20px;
  width: 30px;
}
</style>